import { useRouteStore } from '@/store/modules/routeStore'
import { useMenuStore } from '@/store/modules/menuStore'
import layout from '@/layout/index.vue'
const modules = import.meta.glob('../view/**/**.vue')

export const dynamicRotuer = async (to: any, from: any, next: any) => {
  // 判断当前用户是否登录
  let session = localStorage.getItem('session')
  if (to.path == '/login' && session) {
    next({ path: '/home' })
    return
  } else if (to.path == '/login' && !session) {
    next()
    return
  } else if (to.path != '/login' && !session) {
    next({ path: '/login' })
    return
  }
  const routeStore = useRouteStore()
  // 判断VueX中的缓存是否有菜单列表
  let routes = routeStore.flatRoutes
  const menuStore = useMenuStore()
  if (routes.length) {
    if (routes.find((item: any) => item.path === to.path)) {
      menuStore.setActiveMenu(to.path)
    }
    next()
  } else {
    await routeStore.setRoutes()
    menuStore.setActiveMenu(to.path)
    next({ path: to.path, query: to.query })
  }
}

/**
 * 把从后台获取到的路由数据格式化成vueRouter需要的格式
 * @param {Array} routes 需要格式化路由列表
 * @returns
 */
export const formatRouter = (router: any, routes: any) => {
  addRouteFun(router, routes)
}
/**
 * 嵌套回调把路由添加到路由实例上
 * @returns
 */
function addRouteFun(router: any, routes: any[], prName?: string) {
  routes.forEach((route: any) => {
    let component: any =
      route.component == 'layout'
        ? layout
        : modules[`../view${route.component}.vue`]

    if (route.path && route.name && route.component) {
      let newRouter = {
        path: route.path,
        name: route.name,
        component,
        redirect: route.redirect,
        meta: {
          title: route.meta.title,
          icon: route.meta.icon,
          hide: route.meta.hide,
        },
      }

      if (prName) {
        router.addRoute(prName, newRouter)
      } else {
        router.addRoute(newRouter)
      }
      if (route.children) {
        addRouteFun(router, route.children, route.name)
      }
    }
  })
}

/**
 * 实现数组扁平化的方法---处理多重数组转换成vueRouter的路由
 */
export const flatRouterList = (routes: any[]) => {
  return routes.reduce((pre, cur) => {
    return cur.children ? pre.concat(cur.children) : pre.concat(cur)
  }, [])
}
